<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Log;
use App\Http\Controllers\Controller;
use App\Http\Query\SaleQuery;

class SaleController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        logger("#####セール品ーユーザー認証");
        $this->middleware('checkAdmin'); // ユーザー認証
    }

    /**
     * 初期表示
     */
    public function index()
    {
       try{
            $saleQuery = new SaleQuery();
            $allSale = $saleQuery->getAllSaleInfo();
            return view('admin/sale_master', compact('allSale'));
         }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    /**
     * セール品追加画面表示
     */
    public function showAddSaleView()
    {
        try{
              $saleQuery = new SaleQuery();
              // カテゴリのデータを取る
              $categoryInfo = $saleQuery->getCategoryInfo();
              // 商品のデータを取る
              $goodsInfo = $saleQuery->getGoodsInfo();
              // 会社のデータを取る
              $companyInfo = $saleQuery->getCompanyInfo();
              $allInfo = [
                    $categoryInfo,
                    $goodsInfo,
                    $companyInfo
                ];
              return view('admin.sale_add', array(
                    'allInfo' => $allInfo
                ));
          }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    /**
     * セール品保存
     */
    public function addSaleGoodsMaster(Request $request)
    {
       try{
                $saleQuery = new SaleQuery();
                // セール名称、期間、トップページ表示、画像を取る sale_master
                $saleMasterInfo = $request->input('SaleMaster');

                $file = $request->file('photo');
                if (empty($file)) {
                    echo "<script type=\"text/javascript\">alert(\"アップロードの画像を選択してください!\");window.history.go(-1);</script>";
                    exit();
                }
                $allowed_extensions = [
                    "png",
                    "jpg",
                    "gif",
                    "jpeg",
                    "bmp",
                    "webp"
                ];
                if ($file->getClientOriginalExtension() && ! in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
                    return [
                        'error' => 'You may only upload png, jpg，jpeg，bmp or gif.'
                    ];
                }
                // public フォルダのパス uploads/images
                $destinationPath = 'uploadsale/images/';
                $extension = $file->getClientOriginalExtension();
                // 随机生成的字符串,可以自行拼接图片名字
                $fileName = str_random(10) . '.' . $extension;
                $file->move($destinationPath, $fileName);
                // $filePath = asset($destinationPath.$fileName);
                $ext_name = substr(strstr($fileName, '.'), 1);

                // セール名称、期間、トップページ表示、画像を保存する sale_master
                if (end($saleMasterInfo) != "1") {
                    $saleMasterInfo['display_flg'] = 0;
                }
                $saleMasterInfo['image_url'] = '/ecsite/uploadsale/images/';
                $saleMasterInfo['image_file_name'] = $fileName;
                $saleMasterInfo['image_extension'] = $ext_name;
                $saleMasterInfo['delete_flg'] = 0;
                $saleMasterInfo['created_at'] = now();
                $saleMasterInfo['updated_at'] = now();
                $saleId = $saleQuery->saveSaleMaster($saleMasterInfo);

                if (! empty($saleId)) {
                    // 商品IDを取る sale_goods_master
                    $saleGoodsInfo = $request->input('SaleGoodsMaster');

                    $saleGoodsInfo['sale_id'] = $saleId;
                    $saleGoodsInfo['goods_id'] = strstr(current($saleGoodsInfo), ',', true);
                    $saleGoodsInfo['delete_flg'] = 0;
                    $saleGoodsInfo['created_at'] = now();
                    $saleGoodsInfo['updated_at'] = now();

                    // 適用対象 を取る sale_corp_master
                    $saleCorpMasterInfo = $request->input('SaleCorpMaster');

                    $saleCorpMasterInfo['sale_id'] = $saleId;
                    $saleCorpMasterInfo['delete_flg'] = 0;
                    $saleCorpMasterInfo['created_at'] = now();
                    $saleCorpMasterInfo['updated_at'] = now();

                    // セール条件 を取る sale_condiction
                    $saleCondictionInfo = $request->input('SaleCondiction');
                    $saleCondictionInfoTwo = $request->input('SaleCondictionTwo');
                    $saleCondictionInfoThree = $request->input('SaleCondictionThree');

                    if(in_array('', $saleCondictionInfo)){
                        echo "<script type=\"text/javascript\">alert(\"セール条件１が空数値ではあります!\");window.history.go(-1);</script>";
                        exit();
                    }
                    if(in_array('', $saleCondictionInfoTwo)){
                        echo "<script type=\"text/javascript\">alert(\"セール条件２が空数値ではあります!\");window.history.go(-1);</script>";
                        exit();
                    }
                    if(in_array('', $saleCondictionInfoThree)){
                        echo "<script type=\"text/javascript\">alert(\"セール条件３が空数値ではあります!\");window.history.go(-1);</script>";
                        exit();
                    }
                    $flag = $saleQuery->saveSaleGoodsCorpCondiction($saleGoodsInfo, $saleCorpMasterInfo, $saleCondictionInfo,$saleCondictionInfoTwo,$saleCondictionInfoThree, $saleId);

                    if ($flag) {
                        return redirect('/admin/sale_master')->with('success', '追加成功');
                    }
                 }
            }catch (\Exception $e){
                \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    /**
     * セール品削除
     */
    public function deleteSaleMaster(Request $request)
    {
       try{
            $saleId = $request->input('sale_id');

            $saleQuery = new SaleQuery();
            $flag = $saleQuery->deleteSaleMaster($saleId);

            if ($flag) {
                return redirect('/admin/sale_master')->with('success', '削除成功');
            }
          }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    /**
     * セール品修正
     */
    public function updateSaleMaster(Request $request)
    {
       try{
            $saleId = $request->input('sale_id');

            $saleQuery = new SaleQuery();
            $allInfo = $saleQuery->selectSaleMasterById($saleId);

            $saleCondiction = $saleQuery->selectSaleCondictionById($saleId);

            // カテゴリのデータを取る
            $categoryInfo = $saleQuery->getCategoryInfo();
            // 商品のデータを取る
            $goodsInfo = $saleQuery->getGoodsInfo();
            // 会社のデータを取る
            $companyInfo = $saleQuery->getCompanyInfo();

            $allInfoUpdate = [
                $allInfo,
                $categoryInfo,
                $goodsInfo,
                $companyInfo,
                $saleCondiction
            ];
            Log::info($allInfoUpdate[4]);
            return view('admin.sale_add', array(
                'allInfoUpdate' => $allInfoUpdate
            ));
          }catch (\Exception $e){
              \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
       }
    }

    /**
     * セール品修正save
     */
    public function updateSale(Request $request)
    {
       try{
            $saleQuery = new SaleQuery();
            // セール名称、期間、トップページ表示、画像を取る sale_master
            $saleMasterInfo = $request->input('SaleMaster');
            $filesrc = $request->input('filesrc');
            $file = $request->file('photo');

            if (empty($file)) {
                $fName = explode('/', $filesrc);
                $fileName = $fName[3];
                $ext_name = substr(strstr($fileName, '.'), 1);
            } else {
                $allowed_extensions = [
                    "png",
                    "jpg",
                    "gif",
                    "jpeg",
                    "bmp",
                    "webp"
                ];
                if ($file->getClientOriginalExtension() && ! in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
                    return [
                        'error' => 'You may only upload png, jpg，jpeg，bmp or gif.'
                    ];
                }
                // public フォルダのパス uploads/images
                $destinationPath = 'uploadsale/images/';
                $extension = $file->getClientOriginalExtension();
                // 随机生成的字符串,可以自行拼接图片名字
                $fileName = str_random(10) . '.' . $extension;
                $file->move($destinationPath, $fileName);
                // $filePath = asset($destinationPath.$fileName);
                $ext_name = substr(strstr($fileName, '.'), 1);
            }

            // セール名称、期間、トップページ表示、画像を保存する sale_master
            if (end($saleMasterInfo) != "1") {
                $saleMasterInfo['display_flg'] = 0;
            }
            $saleId = $saleMasterInfo['sale_id'];

            $saleGoodsInfo = $request->input('SaleGoodsMaster');
            $saleGoodsInfo['goods_id'] = strstr(current($saleGoodsInfo), ',', true);
            $goodsId = $saleGoodsInfo['goods_id'];

            // 適用対象 を取る sale_corp_master
            $saleCorpMasterInfo = $request->input('SaleCorpMaster');
            $corpId = $saleCorpMasterInfo['corp_id'];

            // セール条件 を取る sale_condiction
            $saleCondictionInfo = $request->input('SaleCondiction');

            // 修正の時 セール条件 を取る
            $saleCondictionUpdate = $request->input('SaleCondictionUpdate');

            $param = array(
                $saleMasterInfo['sale_name'],
                $saleMasterInfo['start_date'],
                $saleMasterInfo['end_date'],
                $saleMasterInfo['display_flg'],
                '/ecsite/uploadsale/images/',
                $fileName,
                $ext_name,
                $goodsId,
                $corpId,
                $saleId,
                $saleId,
                $saleId
            );
            if(in_array('', $saleCondictionInfo)){
                echo "<script type=\"text/javascript\">alert(\"セール条件が空数値ではあります!\");window.history.go(-1);</script>";
                exit();
            }
            if(in_array('', $saleCondictionUpdate)){
                echo "<script type=\"text/javascript\">alert(\"セール条件が空数値ではあります!\");window.history.go(-1);</script>";
                exit();
            }
            $flag = $saleQuery->updateSaleGoodsCorpCondiction($param, $saleCondictionInfo, $saleCondictionUpdate, $saleId);

            if ($flag) {
                return redirect('/admin/sale_master')->with('success', '修正成功');
            }
          }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

    /**
     * セール品修正
     * 修正の時 削除
     */
    public function deleteSaleCondictionJson(Request $request)
    {
        try{
            $saleCondictionId =$_POST['condictionId'];
            $saleQuery = new SaleQuery();
            $flag = $saleQuery->deleteUpdateCondictionJson($saleCondictionId);

            if(!empty($flag)){
                $status=1;
            }else{
                $status=0;
            }
            echo json_encode($status);
        }catch (\Exception $e){
            \Log::error($e->getFile()." Line:".$e->getLine()." Msg:".$e->getMessage());
        }
    }

}
